<template>
  <div class="user-box">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="个人中心"
      @click-left="$router.go(-1)"
    ></van-nav-bar>
    <!-- /导航栏 -->
    <input @change="onUploaChange" type="file" hidden ref="uploadPic">
    <van-cell @click="$refs.uploadPic.click()" title="头像" is-link>
      <van-image
        class="avatar"
        round
        :src="user.photo"
      />
    </van-cell>
    <van-cell @click="isShowName = true" title="昵称" is-link :value="user.name" />
    <van-cell @click="isShoGender = true" title="性别" is-link :value="user.gender ? '女' : '男'" />
    <van-cell @click="isShowBirthday = true" title="生日" is-link :value="user.birthday || '1900-00-00'" />
    <!-- 编辑 -->
    <!-- 昵称弹层 -->
    <van-popup v-model="isShowName" position="bottom" style="height: 100%">
      <EditName v-if="isShowName" v-model="user.name" @close-popup="isShowName = false" />
    </van-popup>
    <!-- /昵称弹层 -->

    <!-- 性别弹层 -->
    <van-popup v-model="isShoGender" position="bottom" style="height: 50%">
      <EditGender v-if="isShoGender" v-model="user.gender" @close-popup="isShoGender = false" />
    </van-popup>
    <!-- /性别弹层 -->

    <!-- 生日弹层 -->
    <van-popup v-model="isShowBirthday" position="bottom" style="height: 100%">
      <EditBirthday v-if="isShowBirthday" v-model="user.birthday" @close-popup="isShowBirthday = false" />
    </van-popup>
    <!-- /生日弹层 -->

    <!-- 头像弹层 -->
    <van-popup v-model="isShowPhoto" position="bottom" style="height:100%">
      <EditPhoto v-model="user.photo" :img="img" @oncancel="isShowPhoto = false" />
    </van-popup>
    <!-- /头像弹层 -->
    <!-- /编辑 -->
  </div>
</template>

<script>
import { getUserProfile } from '@/api/user.js'
import EditName from './components/edit-name.vue'
import EditGender from './components/edit-gender.vue'
import EditBirthday from './components/edit-birthday.vue'
import EditPhoto from './components/edit-photo.vue'
export default {
  name: 'user',
  data () {
    return {
      user: {},
      isShowName: false, // 昵称显示隐藏弹层
      isShoGender: false, // 性别显示隐藏弹层
      isShowBirthday: false, // 生日显示隐藏弹层
      isShowPhoto: false, // 头像显示隐藏弹层
      img: '' // 选择的图片
    }
  },
  components: {
    EditName,
    EditGender,
    EditBirthday,
    EditPhoto
  },
  created () {
    this.getUserProfile()
  },

  methods: {
    // 加载用户资料
    async getUserProfile () {
      try {
        const { data: res } = await getUserProfile()
        this.user = res.data
      } catch (err) {
        this.$toast('获取失败!')
      }
    },
    // 选择图片
    onUploaChange () {
      const files = this.$refs.uploadPic.files[0]
      const blob = window.URL.createObjectURL(files)
      this.img = blob
      this.isShowPhoto = true
      this.$refs.uploadPic.value = ''
    }
  }
}
</script>

<style scoped lang='less'>
  .user-box {
    .avatar {
      width: 50px;
      height: 50px;
    }
  }
</style>
